//
//  MFAPMNetMonitorModel.m
//  MFAPMManager
//
//  Created by zhang liyu on 2019/5/25.
//

#import "MFAPMNetMonitorModel.h"

#import "UIDevice+MFAPMUtility.h"
#import "MFAPMUtility.h"

@interface MFAPMNetMonitorModel ()

/**
 请求接收到的数据
 */
@property (nonatomic, strong) NSMutableData *receiveData;

@end

@implementation MFAPMNetMonitorModel

#pragma mark - Life Circle

- (instancetype)init{
    self = [super init];
    if(self){
        [self configPropertyActions];
    }
    return self;
}

- (void)configPropertyActions{
    
    //初始化Model的公共属性
    
    self.eventType = 1;
}


#pragma mark - Data Deal Methods

- (void)updateRequestData:(NSURLRequest *)request{
    
    _request = request;
    
    //暂时仅统计HTTP渠道请求，后续有新增时，进行后续更新
    _requestMode = 1;
    
    if([request.URL.absoluteString rangeOfString:@"missfresh"].location != NSNotFound){
        _requestSource = 1;
    }else{
        _requestSource = 2;
    }
    
    _requestMethod = _request.HTTPMethod ? : @"";
    
    _url = request.URL.absoluteString ? : @"";
    
    _domain = request.URL.host ? : @"";
    
    _ip = [UIDevice mfapm_getDeviceIPAddresses] ? : @"";
    
    _requestParameter = request.URL.query ? : @"";
    
    //有解析不了的data数据，应该是加密数据，暂时并不上传
    _requestBody = [MFAPMUtility convertJSONStringFromData:[MFAPMUtility getHttpBodyFromRequest:_request]] ? : @"";
    
    _requestHeaders = [MFAPMUtility convertJSONStringFromObject:_request.allHTTPHeaderFields] ? : @"";
    
    //初始化response的默认值
    _statusCode = @"";
    _responseCode = @"";
    _receiveData = [NSMutableData data];
}

- (void)updateResponseData:(NSURLResponse *)response{
    _response = response;
    _statusCode = [NSString stringWithFormat:@"%ld",((NSHTTPURLResponse *)response).statusCode];
    _responseMIMEType = response.MIMEType ?: @"";
}

- (void)updateErrorData:(NSError *)error{
    _responseMessage = error.localizedDescription ? : @"";
    // 网络请求结束
}

- (void)updateReceiveData:(NSData *)data{
    [_receiveData appendData:data];
}

- (void)finishRequest{
    [self responseSerialization];
}

- (void)responseSerialization {
    if (_receiveData.length > 0) {
        NSDictionary *responseBodyDict = [NSJSONSerialization JSONObjectWithData:self.receiveData options:NSJSONReadingMutableContainers error:nil];
        
        _responseBody = [MFAPMUtility convertJSONStringFromObject:responseBodyDict] ? : @"";

        NSNumber *code = [responseBodyDict objectForKey:@"code"];
        if ([code isKindOfClass:[NSNumber class]]) {
            _responseCode = [NSString stringWithFormat:@"%ld", code.integerValue];
        }else if ([code isKindOfClass:[NSString class]]){
            _responseCode = [NSString stringWithFormat:@"%ld", ((NSString *)[responseBodyDict objectForKey:@"code"]).integerValue];
        }
    }
}

@end
